<template>
    <view
        class="tui-scroll-top_box"
        v-show="visible && toggle"
        :style="{ bottom: bottom + 'rpx', right: right + 'rpx' }"
    >
        <view v-for="icon in icons" class="tui-scroll-top_item" @tap.stop="icon.click">
            <image class="tui-scroll-top_img" :src="icon.imageUrl"></image>
        </view>
        <view class="tui-scroll-top_item" v-show="visible && toggle" @tap.stop="goTop">
            <image class="tui-scroll-top_img" :src="topIcon"></image>
        </view>
    </view>
</template>

<script lang="ts">
type IconBtn = {
    imageUrl: string
    click: Function
}
export default {
    name: 'tuiScrollTop',
    emits: ['index'],
    props: {
        //回顶部按钮距离底部距离 rpx
        bottom: {
            type: Number,
            default: 180
        },
        //回顶部按钮距离右侧距离 rpx
        right: {
            type: Number,
            default: 25
        },
        //距离顶部多少距离显示 px
        top: {
            type: Number,
            default: 200
        },
        //滚动距离
        scrollTop: {
            type: Number,
            required: true
        },
        //回顶部滚动时间
        duration: {
            type: Number,
            default: 240
        },
        //回顶部icon
        topIcon: {
            type: String,
            default: '/static/icon/icon-up.png'
        },
        icons: {
            type: Array<IconBtn>
        }
    },
    watch: {
        scrollTop(newValue, oldValue) {
            this.change()
        }
    },
    data() {
        return {
            //判断是否显示
            visible: false,
            //控制显示，主要解决调用api滚到顶部fixed元素抖动的问题
            toggle: true
        }
    },
    methods: {
        goTop: function () {
            this.toggle = false
            uni.pageScrollTo({
                scrollTop: 0,
                duration: this.duration
            })
            setTimeout(() => {
                this.toggle = true
            }, 220)
        },
        goIndex: function () {
            this.$emit('index', {})
        },
        change() {
            let show = this.scrollTop > this.top
            if ((show && this.visible) || (!show && !this.visible)) {
                return
            }
            this.visible = show
        }
    }
}
</script>

<style lang="scss" scoped>
$m-scroll-top-size: 60rpx;
.tui-scroll-top_box {
    width: $m-scroll-top-size;
    position: fixed;
    z-index: 9999;
    right: 30rpx;
    bottom: 30rpx;
    font-weight: 400;
    background-color: #87828275;
    padding: 10rpx;
    border-radius: 40rpx;
}

.tui-scroll-top_item {
    width: $m-scroll-top-size;
    height: $m-scroll-top-size;
    position: relative;
}

.tui-scroll-item_top {
    margin-top: 30rpx;
}

.tui-scroll-top_img {
    width: $m-scroll-top-size;
    height: $m-scroll-top-size;
    display: block;
}
</style>
